package Greddy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 56.合并区间  10.16
 * 以数组 intervals 表示若干个区间的集合，其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间，并返回 一个不重叠的区间数组，该数组需恰好覆盖输入中的所有区间 。
 */
public class merge {
    /**
     * 一刷
     * 二刷思路更清楚，一刷代码更简洁
     */
    public int[][] merge(int[][] intervals) {

        if (intervals.length == 0 || intervals.length == 1) return intervals;
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int end = intervals[0][1];
        int start = intervals[0][0];
        List<int[]> mergedIntervals = new ArrayList<>();

        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= end) {
                end = Math.max(intervals[i][1], end);
            } else {
               mergedIntervals.add(new int[]{start, end});
               start = intervals[i][0];
               end = intervals[i][1];
            }
        }
        mergedIntervals.add(new int[]{start, end});
        return mergedIntervals.toArray(new int[mergedIntervals.size()][]);
    }

    /**
     * 二刷
     */
    public int[][] merge2(int[][] intervals) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        int start = intervals[0][0];
        int end = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] > end) {
                List<Integer> list = new ArrayList<>();
                list.add(start);
                list.add(end);
                res.add(list);
                start = intervals[i][0];
                end = intervals[i][1];
            } else {
                end = Math.max(end, intervals[i][1]);
            }
        }
        List<Integer> list = new ArrayList<>();
        list.add(start);
        list.add(end);
        res.add(list);

        int arr[][] = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            arr[i][0] = res.get(i).get(0);
            arr[i][1] = res.get(i).get(1);
        }
        return arr;
    }
}
